// HSS.Forms.Docking.DockPane.cs
// ----------------------------------------------------------------------------
// Licensed under the MIT license
// http://www.opensource.org/licenses/mit-license.html
// ----------------------------------------------------------------------------
// HighSpeed-Solutions, LLC
// Copyright (c) 2001-2010
// ----------------------------------------------------------------------------
// File:       DockPane.cs
// Author:     HSS\gbanta
// Created:    08/12/2010
// Modified:   12/04/2010
// ----------------------------------------------------------------------------
namespace HSS.Forms.Docking
{
	#region Using Directives
	using System;
	using System.ComponentModel;
	using System.Diagnostics.CodeAnalysis;
	using System.Drawing;
	using System.Security.Permissions;
	using System.Windows.Forms;
	#endregion

	#region DockPane
	/// <summary>
	/// DockPane
	/// </summary>
	[ToolboxItem(false)]
	public partial class DockPane : UserControl, IDockDragSource
	{
		#region AppearanceStyle
		/// <summary>
		/// AppearanceStyle
		/// </summary>
		public enum AppearanceStyle
		{
			/// <summary>
			/// As a ToolWindow
			/// </summary>
			ToolWindow,
			/// <summary>
			/// As a Document
			/// </summary>
			Document
		}
		#endregion

		#region HitTestArea
		/// <summary>
		/// HitTestArea
		/// </summary>
		enum HitTestArea
		{
			/// <summary>
			/// Caption Area
			/// </summary>
			Caption,
			/// <summary>
			/// TabStrip Area
			/// </summary>
			TabStrip,
			/// <summary>
			/// Content Area
			/// </summary>
			Content,
			/// <summary>
			/// None
			/// </summary>
			None
		}
		struct HitTestResult
		{
			public HitTestArea HitArea;
			public int Index;

			public HitTestResult(HitTestArea hitTestArea, int index)
			{
				HitArea = hitTestArea;
				Index = index;
			}
		}
		#endregion

		#region Events
		static readonly object DockStateChangedEvent = new object();
		/// <summary>
		/// DockStateChanged Event
		/// </summary>
		public event EventHandler DockStateChanged
		{
			add { Events.AddHandler(DockStateChangedEvent, value); }
			remove { Events.RemoveHandler(DockStateChangedEvent, value); }
		}
		/// <summary>
		/// OnDockStateChanged
		/// </summary>
		/// <param name="e">EventArgs</param>
		protected virtual void OnDockStateChanged(EventArgs e)
		{
			EventHandler handler = (EventHandler)Events[DockStateChangedEvent];
			if (handler != null)
				handler(this, e);
		}

		static readonly object IsActivatedChangedEvent = new object();
		/// <summary>
		/// IsActivatedChanged Event
		/// </summary>
		public event EventHandler IsActivatedChanged
		{
			add { Events.AddHandler(IsActivatedChangedEvent, value); }
			remove { Events.RemoveHandler(IsActivatedChangedEvent, value); }
		}
		/// <summary>
		/// OnIsActivatedChanged
		/// </summary>
		/// <param name="e">EventArgs</param>
		protected virtual void OnIsActivatedChanged(EventArgs e)
		{
			EventHandler handler = (EventHandler)Events[IsActivatedChangedEvent];
			if (handler != null)
				handler(this, e);
		}

		static readonly object IsActiveDocumentPaneChangedEvent = new object();
		/// <summary>
		/// IsActiveDocumentPaneChanged Event
		/// </summary>
		public event EventHandler IsActiveDocumentPaneChanged
		{
			add { Events.AddHandler(IsActiveDocumentPaneChangedEvent, value); }
			remove { Events.RemoveHandler(IsActiveDocumentPaneChangedEvent, value); }
		}
		/// <summary>
		/// OnIsActiveDocumentPaneChanged
		/// </summary>
		/// <param name="e">EventArgs</param>
		protected virtual void OnIsActiveDocumentPaneChanged(EventArgs e)
		{
			EventHandler handler = (EventHandler)Events[IsActiveDocumentPaneChangedEvent];
			if (handler != null)
				handler(this, e);
		}

		#endregion

		#region Fields
		int _countRefreshStateChange = 0;
		#endregion

		#region Constructor

		/// <summary>
		/// ctor
		/// </summary>
		/// <param name="content">IDockContent</param>
		/// <param name="visibleState">DockState</param>
		/// <param name="show">bool</param>
		internal protected DockPane(IDockContent content, DockState visibleState, bool show)
		{
			InternalConstruct(content, visibleState, false, Rectangle.Empty, null, DockAlignment.Right, 0.5, show);
		}

		/// <summary>
		/// ctor
		/// </summary>
		/// <param name="content">IDockContent</param>
		/// <param name="floatWindow">FloatWindow</param>
		/// <param name="show">bool</param>
		[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")]
		internal protected DockPane(IDockContent content, FloatWindow floatWindow, bool show)
		{
			if (floatWindow == null)
				throw new ArgumentNullException("floatWindow");

			InternalConstruct(content, DockState.Float, false, Rectangle.Empty, floatWindow.NestedPanes.GetDefaultPreviousPane(this), DockAlignment.Right, 0.5, show);
		}

		/// <summary>
		/// ctor
		/// </summary>
		/// <param name="content">IDockContent</param>
		/// <param name="previousPane">DockPane</param>
		/// <param name="alignment">DockAlignment</param>
		/// <param name="proportion">double</param>
		/// <param name="show">bool</param>
		internal protected DockPane(IDockContent content, DockPane previousPane, DockAlignment alignment, double proportion, bool show)
		{
			if (previousPane == null)
				throw (new ArgumentNullException("previousPane"));
			InternalConstruct(content, previousPane.DockState, false, Rectangle.Empty, previousPane, alignment, proportion, show);
		}

		/// <summary>
		/// ctor
		/// </summary>
		/// <param name="content">IDockContent</param>
		/// <param name="floatWindowBounds">Rectangle</param>
		/// <param name="show">bool</param>
		[SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")]
		internal protected DockPane(IDockContent content, Rectangle floatWindowBounds, bool show)
		{
			InternalConstruct(content, DockState.Float, true, floatWindowBounds, null, DockAlignment.Right, 0.5, show);
		}

		#endregion

		#region Properties

		/// <summary>
		/// IsActivated
		/// </summary>
		public bool IsActivated
		{
			get { return _isActivated; }
		} bool _isActivated = false;

		/// <summary>
		/// CaptionText
		/// </summary>
		public virtual string CaptionText
		{
			get { return ActiveContent == null ? string.Empty : ActiveContent.DockHandler.TabText; }
		}

		/// <summary>
		/// Contents
		/// </summary>
		public DockContentCollection Contents
		{
			get { return _contents; }
		} DockContentCollection _contents;

		/// <summary>
		/// DisplayingContents
		/// </summary>
		public DockContentCollection DisplayingContents
		{
			get { return _displayingContents; }
		} DockContentCollection _displayingContents;

		/// <summary>
		/// DockPanel
		/// </summary>
		public DockPanel DockPanel
		{
			get { return _dockPanel; }
		} DockPanel _dockPanel;

		/// <summary>
		/// DockWindow
		/// </summary>
		public DockWindow DockWindow
		{
			get { return (_nestedDockingStatus.NestedPanes == null) ? null : _nestedDockingStatus.NestedPanes.Container as DockWindow; }
			set
			{
				DockWindow oldValue = DockWindow;
				if (oldValue == value)
					return;

				DockTo(value);
			}
		}

		/// <summary>
		/// FloatWindow
		/// </summary>
		public FloatWindow FloatWindow
		{
			get { return (_nestedDockingStatus.NestedPanes == null) ? null : _nestedDockingStatus.NestedPanes.Container as FloatWindow; }
			set
			{
				FloatWindow oldValue = FloatWindow;
				if (oldValue == value)
					return;

				DockTo(value);
			}
		}

		/// <summary>
		/// NestedDockingStatus
		/// </summary>
		public NestedDockingStatus NestedDockingStatus
		{
			get { return _nestedDockingStatus; }
		} NestedDockingStatus _nestedDockingStatus;

		/// <summary>
		/// IsFloat
		/// </summary>
		public bool IsFloat
		{
			get { return _isFloat; }
		} bool _isFloat;

		/// <summary>
		/// NestedPanesContainer
		/// </summary>
		public INestedPanesContainer NestedPanesContainer
		{
			get
			{
				if (NestedDockingStatus.NestedPanes == null)
					return null;
				else
					return NestedDockingStatus.NestedPanes.Container;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		public DockState DockState
		{
			get { return _dockState; }
			set
			{
				SetDockState(value);
			}
		} DockState _dockState = DockState.Unknown;

		/// <summary>
		/// IsHidden
		/// </summary>
		public bool IsHidden
		{
			get { return _isHidden; }
		} bool _isHidden = true;

		/// <summary>
		/// ActiveContent
		/// </summary>
		public virtual IDockContent ActiveContent
		{
			get { return _activeContent; }
			set
			{
				if (ActiveContent == value)
					return;

				if (value != null)
				{
					if (!DisplayingContents.Contains(value))
						throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue));
				}
				else
				{
					if (DisplayingContents.Count != 0)
						throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue));
				}

				IDockContent oldValue = _activeContent;

				if (DockPanel.ActiveAutoHideContent == oldValue)
					DockPanel.ActiveAutoHideContent = null;

				_activeContent = value;

				if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi && DockState == DockState.Document)
				{
					if (_activeContent != null)
						_activeContent.DockHandler.Form.BringToFront();
				}
				else
				{
					if (_activeContent != null)
						_activeContent.DockHandler.SetVisible();
					if (oldValue != null && DisplayingContents.Contains(oldValue))
						oldValue.DockHandler.SetVisible();
					if (IsActivated && _activeContent != null)
						_activeContent.DockHandler.Activate();
				}

				if (FloatWindow != null)
					FloatWindow.SetText();

				if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi &&
					DockState == DockState.Document)
					RefreshChanges(false);  // delayed layout to reduce screen flicker
				else
					RefreshChanges();

				if (_activeContent != null)
					TabStripControl.EnsureTabVisible(_activeContent);
			}
		} IDockContent _activeContent = null;

		/// <summary>
		/// AllowDockDragAndDrop
		/// </summary>
		public virtual bool AllowDockDragAndDrop
		{
			get { return _allowDockDragAndDrop; }
			set { _allowDockDragAndDrop = value; }
		} bool _allowDockDragAndDrop = true;

		/// <summary>
		/// IsActiveDocumentPane
		/// </summary>
		public bool IsActiveDocumentPane
		{
			get { return _isActiveDocumentPane; }
		} bool _isActiveDocumentPane = false;

		/// <summary>
		/// IsAutoHide
		/// </summary>
		public bool IsAutoHide
		{
			get { return DockHelper.IsDockStateAutoHide(DockState); }
		}

		/// <summary>
		/// Appearance
		/// </summary>
		public AppearanceStyle Appearance
		{
			get { return (DockState == DockState.Document) ? AppearanceStyle.Document : AppearanceStyle.ToolWindow; }
		}

		internal DockPaneStripBase TabStripControl
		{
			get { return _tabStripControl; }
		} DockPaneStripBase _tabStripControl;

		internal IDisposable AutoHidePane
		{
			get { return _autoHidePane; }
			set { _autoHidePane = value; }
		} IDisposable _autoHidePane = null;

		internal object AutoHideTabs
		{
			get { return _autoHideTabs; }
			set { _autoHideTabs = value; }
		} object _autoHideTabs = null;

		internal bool HasTabPageContextMenu
		{
			get { return TabPageContextMenu != null; }
		}

		internal void ShowTabPageContextMenu(Control control, Point position)
		{
			object menu = TabPageContextMenu;

			if (menu == null)
				return;

			ContextMenuStrip contextMenuStrip = menu as ContextMenuStrip;
			if (contextMenuStrip != null)
			{
				contextMenuStrip.Show(control, position);
				return;
			}

			ContextMenu contextMenu = menu as ContextMenu;
			if (contextMenu != null)
				contextMenu.Show(this, position);
		}

		internal Rectangle ContentRectangle
		{
			get
			{
				Rectangle rectWindow = DisplayingRectangle;
				Rectangle rectCaption = CaptionRectangle;
				Rectangle rectTabStrip = TabStripRectangle;

				int x = rectWindow.X;
				int y = rectWindow.Y + (rectCaption.IsEmpty ? 0 : rectCaption.Height) +
					(DockState == DockState.Document ? rectTabStrip.Height : 0);
				int width = rectWindow.Width;
				int height = rectWindow.Height - rectCaption.Height - rectTabStrip.Height;

				Rectangle rect = new Rectangle(x, y, width, height);

				if (this.DockState == DockState.Document)
				{
					if (DockPanel.Instance.ShowDocumentBoder)
						rect.Inflate(-5, -5);
				}
				else if (IsAutoHide)
					rect.Inflate(-1, -1);
				else if (!IsFloat)
					rect = new Rectangle(x + 1, y + 1, width - 2, height - 4);

				return rect;
			}
		}

		internal Rectangle TabStripRectangle
		{
			get
			{
				if (Appearance == AppearanceStyle.ToolWindow)
					return TabStripRectangle_ToolWindow;
				else
					return TabStripRectangle_Document;
			}
		}

		internal Rectangle DisplayingRectangle
		{
			get { return ClientRectangle; }
		}

		Rectangle TabStripRectangle_ToolWindow
		{
			get
			{
				if (DisplayingContents.Count <= 1 || IsAutoHide)
					return Rectangle.Empty;

				Rectangle rectWindow = DisplayingRectangle;

				int width = rectWindow.Width;
				int height = TabStripControl.MeasureHeight();
				int x = rectWindow.X;
				int y = rectWindow.Bottom - height;
				Rectangle rectCaption = CaptionRectangle;
				if (rectCaption.Contains(x, y))
					y = rectCaption.Y + rectCaption.Height;

				return new Rectangle(x, y, width, height);
			}
		}

		Rectangle TabStripRectangle_Document
		{
			get
			{
				if (DisplayingContents.Count == 0)
					return Rectangle.Empty;

				if (DisplayingContents.Count == 1 && DockPanel.DocumentStyle == DocumentStyle.DockingSdi)
					return Rectangle.Empty;

				Rectangle rectWindow = DisplayingRectangle;
				int x = rectWindow.X;
				int y = rectWindow.Y;
				int width = rectWindow.Width;
				int height = TabStripControl.MeasureHeight();

				return new Rectangle(x, y, width, height);
			}
		}

		Rectangle CaptionRectangle
		{
			get
			{
				if (!HasCaption)
					return Rectangle.Empty;

				Rectangle rectWindow = DisplayingRectangle;
				int x, y, width, height;

				Rectangle rect;
				x = rectWindow.X;
				y = rectWindow.Y;
				width = rectWindow.Width;
				height = CaptionControl.MeasureHeight();
				rect = new Rectangle(x, y, width, height);

				if (this.DockState != DockState.Document)
				{
					rect.X++;
					rect.Y++;
					rect.Width = rect.Width - 2;
				}

				return rect;
			}
		}

		DockPaneCaptionBase CaptionControl
		{
			get { return _captionControl; }
		} DockPaneCaptionBase _captionControl;

		object TabPageContextMenu
		{
			get
			{
				IDockContent content = ActiveContent;

				if (content == null)
					return null;

				if (content.DockHandler.TabPageContextMenuStrip != null)
					return content.DockHandler.TabPageContextMenuStrip;
				else if (content.DockHandler.TabPageContextMenu != null)
					return content.DockHandler.TabPageContextMenu;
				else
					return null;
			}
		}

		bool HasCaption
		{
			get
			{
				if (DockState == DockState.Document ||
					DockState == DockState.Hidden ||
					DockState == DockState.Unknown ||
					(DockState == DockState.Float && FloatWindow.VisibleNestedPanes.Count <= 1))
					return false;
				else
					return true;
			}
		}

		#endregion

		#region Methods

		/// <summary>
		/// Show
		/// </summary>
		public new void Show()
		{
			Activate();
		}

		/// <summary>
		/// Activate
		/// </summary>
		public void Activate()
		{
			if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel.ActiveAutoHideContent != ActiveContent)
				DockPanel.ActiveAutoHideContent = ActiveContent;
			else if (!IsActivated && ActiveContent != null)
				ActiveContent.DockHandler.Activate();
		}

		/// <summary>
		/// SetDockState
		/// </summary>
		/// <param name="value">DockState</param>
		/// <returns>DockPane</returns>
		public DockPane SetDockState(DockState value)
		{
			if (value == DockState.Unknown || value == DockState.Hidden)
				throw new InvalidOperationException(Strings.DockPane_SetDockState_InvalidState);

			if ((value == DockState.Float) == this.IsFloat)
			{
				InternalSetDockState(value);
				return this;
			}

			if (DisplayingContents.Count == 0)
				return null;

			IDockContent firstContent = null;
			for (int i = 0; i < DisplayingContents.Count; i++)
			{
				IDockContent content = DisplayingContents[i];
				if (content.DockHandler.IsDockStateValid(value))
				{
					firstContent = content;
					break;
				}
			}
			if (firstContent == null)
				return null;

			firstContent.DockHandler.DockState = value;
			DockPane pane = firstContent.DockHandler.Pane;
			DockPanel.SuspendLayout(true);
			for (int i = 0; i < DisplayingContents.Count; i++)
			{
				IDockContent content = DisplayingContents[i];
				if (content.DockHandler.IsDockStateValid(value))
					content.DockHandler.Pane = pane;
			}
			DockPanel.ResumeLayout(true, true);
			return pane;
		}

		/// <summary>
		/// CloseActiveContent
		/// </summary>
		public void CloseActiveContent()
		{
			CloseContent(ActiveContent);
		}

		/// <summary>
		/// RestoreToPanel
		/// </summary>
		public void RestoreToPanel()
		{
			DockPanel.SuspendLayout(true);

			IDockContent activeContent = DockPanel.ActiveContent;

			for (int i = DisplayingContents.Count - 1; i >= 0; i--)
			{
				IDockContent content = DisplayingContents[i];
				if (content.DockHandler.CheckDockState(false) != DockState.Unknown)
					content.DockHandler.IsFloat = false;
			}

			DockPanel.ResumeLayout(true, true);
		}

		/// <summary>
		/// SetContentIndex
		/// </summary>
		/// <param name="content">IDockContent</param>
		/// <param name="index">int</param>
		public void SetContentIndex(IDockContent content, int index)
		{
			int oldIndex = Contents.IndexOf(content);
			if (oldIndex == -1)
				throw (new ArgumentException(Strings.DockPane_SetContentIndex_InvalidContent));

			if (index < 0 || index > Contents.Count - 1)
				if (index != -1)
					throw (new ArgumentOutOfRangeException(Strings.DockPane_SetContentIndex_InvalidIndex));

			if (oldIndex == index)
				return;
			if (oldIndex == Contents.Count - 1 && index == -1)
				return;

			Contents.Remove(content);
			if (index == -1)
				Contents.Add(content);
			else if (oldIndex < index)
				Contents.AddAt(content, index - 1);
			else
				Contents.AddAt(content, index);

			RefreshChanges();
		}

		/// <summary>
		/// SetNestedDockingProportion
		/// </summary>
		/// <param name="proportion">double</param>
		public void SetNestedDockingProportion(double proportion)
		{
			NestedDockingStatus.SetStatus(NestedDockingStatus.NestedPanes, NestedDockingStatus.PreviousPane, NestedDockingStatus.Alignment, proportion);
			if (NestedPanesContainer != null)
				((Control)NestedPanesContainer).PerformLayout();
		}

		/// <summary>
		/// Float
		/// </summary>
		/// <returns>DockPane</returns>
		public DockPane Float()
		{
			DockPanel.SuspendLayout(true);

			IDockContent activeContent = ActiveContent;

			DockPane floatPane = GetFloatPaneFromContents();
			if (floatPane == null)
			{
				IDockContent firstContent = GetFirstContent(DockState.Float);
				if (firstContent == null)
				{
					DockPanel.ResumeLayout(true, true);
					return null;
				}
				floatPane = DockPanel.DockPaneFactory.CreateDockPane(firstContent, DockState.Float, true);
			}
			SetVisibleContentsToPane(floatPane, activeContent);

			DockPanel.ResumeLayout(true, true);
			return floatPane;
		}

		/// <summary>
		/// DockTo
		/// </summary>
		/// <param name="container">INestedPanesContainer</param>
		/// <returns>DockPane</returns>
		public DockPane DockTo(INestedPanesContainer container)
		{
			if (container == null)
				throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer);

			DockAlignment alignment;
			if (container.DockState == DockState.DockLeft || container.DockState == DockState.DockRight)
				alignment = DockAlignment.Bottom;
			else
				alignment = DockAlignment.Right;

			return DockTo(container, container.NestedPanes.GetDefaultPreviousPane(this), alignment, 0.5);
		}

		/// <summary>
		/// DockTo
		/// </summary>
		/// <param name="container">INestedPanesContainer</param>
		/// <param name="previousPane">DockPane</param>
		/// <param name="alignment">DockAlignment</param>
		/// <param name="proportion">double</param>
		/// <returns>DockPane</returns>
		public DockPane DockTo(INestedPanesContainer container, DockPane previousPane, DockAlignment alignment, double proportion)
		{
			if (container == null)
				throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer);

			if (container.IsFloat == this.IsFloat)
			{
				InternalAddToDockList(container, previousPane, alignment, proportion);
				return this;
			}

			IDockContent firstContent = GetFirstContent(container.DockState);
			if (firstContent == null)
				return null;

			DockPane pane;
			DockPanel.DummyContent.DockPanel = DockPanel;
			if (container.IsFloat)
				pane = DockPanel.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, (FloatWindow)container, true);
			else
				pane = DockPanel.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, container.DockState, true);

			pane.DockTo(container, previousPane, alignment, proportion);
			SetVisibleContentsToPane(pane);
			DockPanel.DummyContent.DockPanel = null;

			return pane;
		}

		/// <summary>
		/// IsDockStateValid
		/// </summary>
		/// <param name="dockState">DockState</param>
		/// <returns>bool</returns>
		public bool IsDockStateValid(DockState dockState)
		{
			foreach (IDockContent content in Contents)
				if (!content.DockHandler.IsDockStateValid(dockState))
					return false;

			return true;
		}

		/// <summary>
		/// OnPaint - custom draw a border around the Pane
		/// </summary>
		/// <param name="e"></param>
		protected override void OnPaint(PaintEventArgs e)
		{
			base.OnPaint(e);

			#region Draw Custom Border

			int borderWidth = 1;
			Color borderColor = DockPanel.Instance.ToolBorderColor;

			if (this.DockState == DockState.Document && DockPanel.Instance.ShowDocumentBoder)
			{
				#region Document Border

				// Border Fill
				borderWidth = 4;
				borderColor = DockPanel.Instance.DocumentFillColor;
				ControlPaint.DrawBorder(e.Graphics, e.ClipRectangle,
						borderColor, borderWidth, ButtonBorderStyle.Solid,
						borderColor, borderWidth, ButtonBorderStyle.Solid,
						borderColor, borderWidth, ButtonBorderStyle.Solid,
						borderColor, borderWidth, ButtonBorderStyle.Solid);

				// Outer Boarder
				Pen p = new Pen(DockPanel.Instance.DocumentBorderColor);
				Rectangle rect = this.ClientRectangle;
				DrawHelper.DrawRoundRect(e.Graphics, p, rect.X, rect.Y, rect.Width - 1, rect.Height - 1, 4);

				// Inner Boarder
				borderWidth = 1;
				borderColor = DockPanel.Instance.DocumentInnerBorderColor;
				rect = this.ContentRectangle;
				rect.Inflate(1, 1);
				ControlPaint.DrawBorder(e.Graphics, rect,
						borderColor, borderWidth, ButtonBorderStyle.Solid,
						borderColor, borderWidth, ButtonBorderStyle.Solid,
						borderColor, borderWidth, ButtonBorderStyle.Solid,
						borderColor, borderWidth, ButtonBorderStyle.Solid);

				#endregion
			}
			else
			{
				#region Non-Floating Tool Border
				if (!this.IsFloat)
				{
					borderWidth = 1;
					borderColor = DockPanel.Instance.ToolBorderColor;

					if (!IsAutoHide)
					{
						Rectangle capcont = Rectangle.Union(this.ContentRectangle, this.CaptionRectangle);
						capcont.Inflate(1, 1);
						ControlPaint.DrawBorder(e.Graphics, capcont,
							borderColor, borderWidth, ButtonBorderStyle.Solid,
							borderColor, borderWidth, ButtonBorderStyle.Solid,
							borderColor, borderWidth, ButtonBorderStyle.Solid,
							borderColor, borderWidth, ButtonBorderStyle.Solid);
					}
					else
					{
						Rectangle rect = e.ClipRectangle;
						ControlPaint.DrawBorder(e.Graphics, rect,
							borderColor, borderWidth, ButtonBorderStyle.Solid,
							borderColor, borderWidth, ButtonBorderStyle.Solid,
							borderColor, borderWidth, ButtonBorderStyle.Solid,
							borderColor, borderWidth, ButtonBorderStyle.Solid);
					}
				}
				#endregion
			}

			#endregion
		}

		/// <summary>
		/// OnControlAdded
		/// </summary>
		/// <param name="e"></param>
		protected override void OnControlAdded(ControlEventArgs e)
		{
			base.OnControlAdded(e);
			this.Invalidate();
		}

		/// <summary>
		/// OnControlRemoved
		/// </summary>
		/// <param name="e"></param>
		protected override void OnControlRemoved(ControlEventArgs e)
		{
			base.OnControlRemoved(e);
			this.Invalidate();
		}

		/// <summary>
		/// WndProc
		/// </summary>
		/// <param name="m">Message</param>
		[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
		protected override void WndProc(ref Message m)
		{

			// Form activiation
			if (m.Msg == (int)Msgs.WM_MOUSEACTIVATE)
				this.Activate();

			// Process as normal
			base.WndProc(ref m);
		}

		/// <summary>
		/// OnLayout
		/// </summary>
		/// <param name="levent">LayoutEventArgs</param>
		protected override void OnLayout(LayoutEventArgs levent)
		{
			SetIsHidden(DisplayingContents.Count == 0);
			if (!IsHidden)
			{
				CaptionControl.Bounds = CaptionRectangle;
				TabStripControl.Bounds = TabStripRectangle;

				SetContentBounds();

				foreach (IDockContent content in Contents)
				{
					if (DisplayingContents.Contains(content))
						if (content.DockHandler.FlagClipWindow && content.DockHandler.Form.Visible)
							content.DockHandler.FlagClipWindow = false;
				}
			}

			base.OnLayout(levent);
		}

		/// <summary>
		/// Cleanup
		/// </summary>
		/// <param name="disposing">bool</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				_dockState = DockState.Unknown;

				if (NestedPanesContainer != null)
					NestedPanesContainer.NestedPanes.Remove(this);

				_activeContent = null; //needs to be cleared 

				Splitter.Dispose();
				if (_autoHidePane != null)
					_autoHidePane.Dispose();

				if (DockPanel != null)
				{
					DockPanel.RemovePane(this);
					_dockPanel = null;
				}

				Controls.Clear(); //causes OnLayout and flushes 'cached' instance.
			}
			base.Dispose(disposing);
		}


		internal void SetIsActiveDocumentPane(bool value)
		{
			if (_isActiveDocumentPane == value)
				return;

			_isActiveDocumentPane = value;
			if (DockState == DockState.Document)
				RefreshChanges();
			OnIsActiveDocumentPaneChanged(EventArgs.Empty);
		}

		internal void SetIsActivated(bool value)
		{
			if (_isActivated == value)
				return;

			_isActivated = value;
			if (DockState != DockState.Document)
				RefreshChanges(false);
			OnIsActivatedChanged(EventArgs.Empty);
		}

		internal void RemoveContent(IDockContent content)
		{
			if (!Contents.Contains(content))
				return;

			Contents.Remove(content);
		}

		internal void AddContent(IDockContent content)
		{
			if (Contents.Contains(content))
				return;

			Contents.Add(content);
		}

		internal void Close()
		{
			Dispose();
		}

		internal void CloseContent(IDockContent content)
		{
			DockPanel dockPanel = DockPanel;
			dockPanel.SuspendLayout(true);

			if (content == null)
				return;

			if (!content.DockHandler.CloseButton)
				return;

			if (content.DockHandler.HideOnClose)
				content.DockHandler.Hide();
			else
				content.DockHandler.Close();

			dockPanel.ResumeLayout(true, true);
		}

		internal void SetContentBounds()
		{
			Rectangle rectContent = ContentRectangle;
			if (DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi)
				rectContent = DockPanel.RectangleToMdiClient(RectangleToScreen(rectContent));

			Rectangle rectInactive = new Rectangle(-rectContent.Width, rectContent.Y, rectContent.Width, rectContent.Height);
			foreach (IDockContent content in Contents)
				if (content.DockHandler.Pane == this)
				{
					if (content == ActiveContent)
						content.DockHandler.Form.Bounds = rectContent;
					else
						content.DockHandler.Form.Bounds = rectInactive;
				}
		}

		internal void RefreshChanges()
		{
			RefreshChanges(true);
		}

		internal void TestDrop(IDockDragSource dragSource, DockOutlineBase dockOutline)
		{
			if (!dragSource.CanDockTo(this))
				return;

			Point ptMouse = Control.MousePosition;

			HitTestResult hitTestResult = GetHitTest(ptMouse);
			if (hitTestResult.HitArea == HitTestArea.Caption)
				dockOutline.Show(this, -1);
			else if (hitTestResult.HitArea == HitTestArea.TabStrip && hitTestResult.Index != -1)
				dockOutline.Show(this, hitTestResult.Index);
		}

		internal void ValidateActiveContent()
		{
			if (ActiveContent == null)
			{
				if (DisplayingContents.Count != 0)
					ActiveContent = DisplayingContents[0];
				return;
			}

			if (DisplayingContents.IndexOf(ActiveContent) >= 0)
				return;

			IDockContent prevVisible = null;
			for (int i = Contents.IndexOf(ActiveContent) - 1; i >= 0; i--)
				if (Contents[i].DockHandler.DockState == DockState)
				{
					prevVisible = Contents[i];
					break;
				}

			IDockContent nextVisible = null;
			for (int i = Contents.IndexOf(ActiveContent) + 1; i < Contents.Count; i++)
				if (Contents[i].DockHandler.DockState == DockState)
				{
					nextVisible = Contents[i];
					break;
				}

			if (prevVisible != null)
				ActiveContent = prevVisible;
			else if (nextVisible != null)
				ActiveContent = nextVisible;
			else
				ActiveContent = null;
		}

		IDockContent GetFocusedContent()
		{
			IDockContent contentFocused = null;
			foreach (IDockContent content in Contents)
			{
				if (content.DockHandler.Form.ContainsFocus)
				{
					contentFocused = content;
					break;
				}
			}

			return contentFocused;
		}

		DockPane GetFloatPaneFromContents()
		{
			DockPane floatPane = null;
			for (int i = 0; i < DisplayingContents.Count; i++)
			{
				IDockContent content = DisplayingContents[i];
				if (!content.DockHandler.IsDockStateValid(DockState.Float))
					continue;

				if (floatPane != null && content.DockHandler.FloatPane != floatPane)
					return null;
				else
					floatPane = content.DockHandler.FloatPane;
			}

			return floatPane;
		}

		IDockContent GetFirstContent(DockState dockState)
		{
			for (int i = 0; i < DisplayingContents.Count; i++)
			{
				IDockContent content = DisplayingContents[i];
				if (content.DockHandler.IsDockStateValid(dockState))
					return content;
			}
			return null;
		}

		HitTestResult GetHitTest(Point ptMouse)
		{
			Point ptMouseClient = PointToClient(ptMouse);

			Rectangle rectCaption = CaptionRectangle;
			if (rectCaption.Contains(ptMouseClient))
				return new HitTestResult(HitTestArea.Caption, -1);

			Rectangle rectContent = ContentRectangle;
			if (rectContent.Contains(ptMouseClient))
				return new HitTestResult(HitTestArea.Content, -1);

			Rectangle rectTabStrip = TabStripRectangle;
			if (rectTabStrip.Contains(ptMouseClient))
				return new HitTestResult(HitTestArea.TabStrip, TabStripControl.HitTest(TabStripControl.PointToClient(ptMouse)));

			return new HitTestResult(HitTestArea.None, -1);
		}

		void InternalSetDockState(DockState value)
		{
			if (_dockState == value)
				return;

			if (null == DockPanel)
				return;

			DockState oldDockState = _dockState;
			INestedPanesContainer oldContainer = NestedPanesContainer;

			_dockState = value;

			SuspendRefreshStateChange();

			IDockContent contentFocused = GetFocusedContent();
			if (contentFocused != null)
				DockPanel.SaveFocus();

			if (!IsFloat)
				DockWindow = DockPanel.DockWindows[DockState];
			else if (FloatWindow == null)
				FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this);

			if (contentFocused != null)
				DockPanel.ContentFocusManager.Activate(contentFocused);

			ResumeRefreshStateChange(oldContainer, oldDockState);
		}

		void SuspendRefreshStateChange()
		{
			_countRefreshStateChange++;
			if (null != DockPanel)
				DockPanel.SuspendLayout(true);
			else
				Console.WriteLine();
		}

		void ResumeRefreshStateChange()
		{
			_countRefreshStateChange--;
			System.Diagnostics.Debug.Assert(_countRefreshStateChange >= 0);
			DockPanel.ResumeLayout(true, true);
		}

		bool IsRefreshStateChangeSuspended
		{
			get { return _countRefreshStateChange != 0; }
		}

		void ResumeRefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState)
		{
			ResumeRefreshStateChange();
			RefreshStateChange(oldContainer, oldDockState);
		}

		void RefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState)
		{
			lock (this)
			{
				if (IsRefreshStateChangeSuspended)
					return;

				SuspendRefreshStateChange();
			}

			DockPanel.SuspendLayout(true);

			IDockContent contentFocused = GetFocusedContent();
			if (contentFocused != null)
				DockPanel.SaveFocus();
			SetParent();

			if (ActiveContent != null)
				ActiveContent.DockHandler.SetDockState(ActiveContent.DockHandler.IsHidden, DockState, ActiveContent.DockHandler.Pane);
			foreach (IDockContent content in Contents)
			{
				if (content.DockHandler.Pane == this)
					content.DockHandler.SetDockState(content.DockHandler.IsHidden, DockState, content.DockHandler.Pane);
			}

			if (oldContainer != null)
			{
				Control oldContainerControl = (Control)oldContainer;
				if (oldContainer.DockState == oldDockState && !oldContainerControl.IsDisposed)
					oldContainerControl.PerformLayout();
			}
			if (DockHelper.IsDockStateAutoHide(oldDockState))
				DockPanel.RefreshActiveAutoHideContent();

			if (NestedPanesContainer.DockState == DockState)
				((Control)NestedPanesContainer).PerformLayout();
			if (DockHelper.IsDockStateAutoHide(DockState))
				DockPanel.RefreshActiveAutoHideContent();

			if (DockHelper.IsDockStateAutoHide(oldDockState) ||
				DockHelper.IsDockStateAutoHide(DockState))
			{
				DockPanel.RefreshAutoHideStrip();
				DockPanel.PerformLayout();
			}

			ResumeRefreshStateChange();

			if (contentFocused != null)
				contentFocused.DockHandler.Activate();

			DockPanel.ResumeLayout(true, true);

			if (oldDockState != DockState)
				OnDockStateChanged(EventArgs.Empty);
		}

		void SetVisibleContentsToPane(DockPane pane)
		{
			SetVisibleContentsToPane(pane, ActiveContent);
		}

		void SetVisibleContentsToPane(DockPane pane, IDockContent activeContent)
		{
			for (int i = 0; i < DisplayingContents.Count; i++)
			{
				IDockContent content = DisplayingContents[i];
				if (content.DockHandler.IsDockStateValid(pane.DockState))
				{
					content.DockHandler.Pane = pane;
					i--;
				}
			}

			if (activeContent.DockHandler.Pane == pane)
				pane.ActiveContent = activeContent;
		}

		void InternalAddToDockList(INestedPanesContainer container, DockPane prevPane, DockAlignment alignment, double proportion)
		{
			if ((container.DockState == DockState.Float) != IsFloat)
				throw new InvalidOperationException(Strings.DockPane_DockTo_InvalidContainer);

			int count = container.NestedPanes.Count;
			if (container.NestedPanes.Contains(this))
				count--;
			if (prevPane == null && count > 0)
				throw new InvalidOperationException(Strings.DockPane_DockTo_NullPrevPane);

			if (prevPane != null && !container.NestedPanes.Contains(prevPane))
				throw new InvalidOperationException(Strings.DockPane_DockTo_NoPrevPane);

			if (prevPane == this)
				throw new InvalidOperationException(Strings.DockPane_DockTo_SelfPrevPane);

			INestedPanesContainer oldContainer = NestedPanesContainer;
			DockState oldDockState = DockState;
			container.NestedPanes.Add(this);
			NestedDockingStatus.SetStatus(container.NestedPanes, prevPane, alignment, proportion);

			if (DockHelper.IsDockWindowState(DockState))
				_dockState = container.DockState;

			RefreshStateChange(oldContainer, oldDockState);
		}

		void SetIsHidden(bool value)
		{
			if (_isHidden == value)
				return;

			_isHidden = value;
			if (DockHelper.IsDockStateAutoHide(DockState))
			{
				DockPanel.RefreshAutoHideStrip();
				DockPanel.PerformLayout();
			}
			else if (NestedPanesContainer != null)
				((Control)NestedPanesContainer).PerformLayout();
		}

		void RefreshChanges(bool performLayout)
		{
			if (IsDisposed)
				return;

			CaptionControl.RefreshChanges();
			TabStripControl.RefreshChanges();
			if (DockState == DockState.Float)
				FloatWindow.RefreshChanges();
			if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel != null)
			{
				DockPanel.RefreshAutoHideStrip();
				DockPanel.PerformLayout();
			}

			if (performLayout)
				PerformLayout();
		}

		void SetParent()
		{
			if (DockState == DockState.Unknown || DockState == DockState.Hidden)
			{
				SetParent(null);
				Splitter.Parent = null;
			}
			else if (DockState == DockState.Float)
			{
				SetParent(FloatWindow);
				Splitter.Parent = FloatWindow;
			}
			else if (DockHelper.IsDockStateAutoHide(DockState))
			{
				SetParent(DockPanel.AutoHideControl);
				Splitter.Parent = null;
			}
			else
			{
				SetParent(DockPanel.DockWindows[DockState]);
				Splitter.Parent = Parent;
			}
		}

		void SetParent(Control value)
		{
			if (Parent == value)
				return;

			//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
			// Workaround of .Net Framework bug:
			// Change the parent of a control with focus may result in the first
			// MDI child form get activated. 
			//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
			IDockContent contentFocused = GetFocusedContent();
			if (contentFocused != null)
				DockPanel.SaveFocus();

			//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

			Parent = value;

			//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
			// Workaround of .Net Framework bug:
			// Change the parent of a control with focus may result in the first
			// MDI child form get activated. 
			//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
			if (contentFocused != null)
				contentFocused.DockHandler.Activate();
			//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
		}

		void InternalConstruct(IDockContent content, DockState dockState, bool flagBounds, Rectangle floatWindowBounds, DockPane prevPane, DockAlignment alignment, double proportion, bool show)
		{
			if (dockState == DockState.Hidden || dockState == DockState.Unknown)
				throw new ArgumentException(Strings.DockPane_SetDockState_InvalidState);

			if (content == null)
				throw new ArgumentNullException(Strings.DockPane_Constructor_NullContent);

			if (content.DockHandler.DockPanel == null)
				throw new ArgumentException(Strings.DockPane_Constructor_NullDockPanel);

			this.SuspendLayout();

			this.SetStyle(ControlStyles.Selectable, false);
			this.SetStyle(ControlStyles.ResizeRedraw |
				ControlStyles.UserPaint |
				ControlStyles.AllPaintingInWmPaint |
				ControlStyles.OptimizedDoubleBuffer, true);

			_isFloat = (dockState == DockState.Float);

			_contents = new DockContentCollection();
			_displayingContents = new DockContentCollection(this);

			_dockPanel = content.DockHandler.DockPanel;
			_dockPanel.AddPane(this);

			_splitter = new SplitterControl(this);

			_nestedDockingStatus = new NestedDockingStatus(this);

			_captionControl = DockPanel.DockPaneCaptionFactory.CreateDockPaneCaption(this);
			_tabStripControl = DockPanel.DockPaneStripFactory.CreateDockPaneStrip(this);
			this.Controls.AddRange(new Control[] { _captionControl, _tabStripControl });

			_dockPanel.SuspendLayout(true);
			if (flagBounds)
				FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds);
			else if (prevPane != null)
				DockTo(prevPane.NestedPanesContainer, prevPane, alignment, proportion);

			SetDockState(dockState);

			if (show)
				content.DockHandler.Pane = this;
			else if (this.IsFloat)
				content.DockHandler.FloatPane = this;
			else
				content.DockHandler.PanelPane = this;

			ResumeLayout();
			DockPanel.ResumeLayout(true, true);

		}
		#endregion

		#region IDockDragSource Members

		#region IDragSource Members

		Control IDragSource.DragControl
		{
			get { return this; }
		}

		#endregion

		bool IDockDragSource.IsDockStateValid(DockState dockState)
		{
			return IsDockStateValid(dockState);
		}

		bool IDockDragSource.CanDockTo(DockPane pane)
		{
			if (!IsDockStateValid(pane.DockState))
				return false;

			if (pane == this)
				return false;

			return true;
		}

		Rectangle IDockDragSource.BeginDrag(Point ptMouse)
		{
			Point location = PointToScreen(new Point(0, 0));
			Size size;

			DockPane floatPane = ActiveContent.DockHandler.FloatPane;
			if (DockState == DockState.Float || floatPane == null || floatPane.FloatWindow.NestedPanes.Count != 1)
				size = DockPanel.DefaultFloatWindowSize;
			else
				size = floatPane.FloatWindow.Size;

			if (ptMouse.X > location.X + size.Width)
				location.X += ptMouse.X - (location.X + size.Width) + Measures.SplitterSize;

			return new Rectangle(location, size);
		}

		/// <summary>
		/// FloatAt
		/// </summary>
		/// <param name="floatWindowBounds">Rectangle</param>
		public void FloatAt(Rectangle floatWindowBounds)
		{
			if (FloatWindow == null || FloatWindow.NestedPanes.Count != 1)
				FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds);
			else
				FloatWindow.Bounds = floatWindowBounds;

			DockState = DockState.Float;
		}
		/// <summary>
		/// DockTo
		/// </summary>
		/// <param name="pane">DockPane</param>
		/// <param name="dockStyle">DockStyle</param>
		/// <param name="contentIndex">int</param>
		public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex)
		{
			if (dockStyle == DockStyle.Fill)
			{
				IDockContent activeContent = ActiveContent;
				for (int i = Contents.Count - 1; i >= 0; i--)
				{
					IDockContent c = Contents[i];
					c.DockHandler.Pane = pane;
					if (contentIndex != -1)
						pane.SetContentIndex(c, contentIndex);
				}
				pane.ActiveContent = activeContent;
			}
			else
			{
				if (dockStyle == DockStyle.Left)
					DockTo(pane.NestedPanesContainer, pane, DockAlignment.Left, 0.5);
				else if (dockStyle == DockStyle.Right)
					DockTo(pane.NestedPanesContainer, pane, DockAlignment.Right, 0.5);
				else if (dockStyle == DockStyle.Top)
					DockTo(pane.NestedPanesContainer, pane, DockAlignment.Top, 0.5);
				else if (dockStyle == DockStyle.Bottom)
					DockTo(pane.NestedPanesContainer, pane, DockAlignment.Bottom, 0.5);

				DockState = pane.DockState;
			}
		}
		/// <summary>
		/// DockTo
		/// </summary>
		/// <param name="panel">DockPanel</param>
		/// <param name="dockStyle">DockStyle</param>
		public void DockTo(DockPanel panel, DockStyle dockStyle)
		{
			if (panel != DockPanel)
				throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, "panel");

			if (dockStyle == DockStyle.Top)
				DockState = DockState.DockTop;
			else if (dockStyle == DockStyle.Bottom)
				DockState = DockState.DockBottom;
			else if (dockStyle == DockStyle.Left)
				DockState = DockState.DockLeft;
			else if (dockStyle == DockStyle.Right)
				DockState = DockState.DockRight;
			else if (dockStyle == DockStyle.Fill)
				DockState = DockState.Document;
		}

		#endregion
	}
	#endregion}
}